<template>
  <div>
    <van-tabs>
      <van-tab title="表单信息">
        <div id="countryPublicity">
          <p style="text-align: center; font-weight: bold; font-size: 20px">村公示信息表</p>
          <div>
            <p class="title">
              <span class="line"></span>
              村公示信息
            </p>
            <div class="upload-pictures">
              <ul>
                <li style="border-bottom: 1px solid #d2d2d2; padding: 10px 0" v-for="(item, index) in ImgData" :key="index">
                  <span style="color: #ff0000; float: left" v-if="item.isBitian">*</span>
                  <p v-if="item.name !== '公示结论'" style="font-weight: bold; color: #1a1a1a">{{ item.name }}</p>
                  <div v-if="item.type == 'input'" class="upload-pictures2">
                    <van-field style="margin: 10px 0" v-model="formData[item.key]" rows="3" autosize type="textarea" :placeholder="'请输入' + item.name" show-word-limit />
                  </div>
                  <div v-if="item.type == 'select'" class="upload-pictures1">
                    <!-- <span style="color: #ff0000;">*</span> -->
                    <van-field required readonly clickable name="picker" :value="formData.SHJG | inUseName(columns)" label="公示结论" placeholder="点击选择公示结论" @click="showPicker = true" />
                    <van-popup v-model="showPicker" position="bottom" get-container="#popup">
                      <van-picker value-key="DICNAME" show-toolbar :columns="columns" @confirm="onConfirm" @cancel="showPicker = false" />
                    </van-popup>
                  </div>
                  <span style="width: 100%; display: inline-block; text-align: right; margin-bottom: 10px; color: #8c8c8c" v-if="item.text">
                    {{ username }}
                    {{ getDate(true) }}
                  </span>
                  <div v-if="item.type == 'uploader'">
                    <van-uploader style="margin-top: 8px" @click-upload="getList(item)" :after-read="afterRead" :before-delete="delectFile" v-model="item.fileList" multiple />
                  </div>
                </li>
              </ul>
              <p class="title">
                <span class="line"></span>
                村公示单
              </p>
              <!-- <p class="top">
                <span style="font-weight: bold">村公示单</span>
                <span @click="download" class="link">链接下载</span>
              </p> -->
              <ul>
                <li>
                  <select-picker :isTime="true" :labels="'公示开始时间'" :selectValue="formData.F_QTRSJSJ" @getMessage="setValue"></select-picker>
                  <select-picker :isTime="true" :labels="'公示结束时间'" :selectValue="formData.F_QTNJSSJ" @getMessage="setValue1"></select-picker>
                </li>
              </ul>
            </div>
            <div class="footer">
              <van-button type="info" style="width: 30%;" @click="sendData">提交</van-button>
              <van-button type="info" style="width: 30%;" @click="saveData">保存</van-button>
              <van-button type="info" style="width: 30%;" @click="blackTable">退回</van-button>
            </div>
          </div>
        </div>
      </van-tab>
      <van-tab title="过程信息">
        <FileData :ROW_GUID="rowguids" :rowData="rowData"></FileData>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import { FileServerProxy, dataTransFile, dataTransFilePreview } from '../../../utils/api'
import selectPicker from '@/utils/selectPicker.vue'
import FileData from '@/components/activity/FileData'
import { GSA_Search, GSA_Add } from '@/common/commonApi'
export default {
  name: 'countryPublicity',
  filters: {
    inUseName: function (msg, data) {
      let name = ''
      data.forEach((item) => {
        if (item.DICID == msg) {
          name = item.DICNAME
        }
      })
      return name
    }
  },
  components: {
    selectPicker,
    FileData
  },
  data() {
    return {
      username: '',
      showPicker: false,
      rowguids: '',
      ImgData: [
        {
          name: '公示回执',
          type: 'uploader',
          groupGuid: '8d7aa8c9-9bba-42f4-aa84-d6ab216e89d2',
          fileList: []
        },
        {
          name: '其他材料',
          type: 'uploader',
          groupGuid: '7eb18ff0-5fe4-47ea-a805-68d7731e2609',
          fileList: []
        },
        {
          name: '村公示远景照片',
          type: 'uploader',
          groupGuid: '563cb165-cf9e-4b6b-ba85-51960abef51f',
          fileList: [],
          isBitian: true
        },
        {
          name: '村公示近景照片',
          type: 'uploader',
          groupGuid: '0313a9ba-75d3-44d0-a5b3-0157fb2b1ea2',
          fileList: [],
          isBitian: true
        },
        {
          name: '会议记录',
          groupGuid: 'e02a07e2-0ab7-4acc-b8e6-77f51854f27a',
          type: 'uploader',
          fileList: [],
          isBitian: true
        },
        {
          name: '屋面色彩',
          key: 'WMSC',
          type: 'input',
          fileList: []
        },
        {
          name: '公示结论',
          key: 'SHJG',
          type: 'select',
          fileList: []
        },
        {
          name: '公示意见',
          key: 'GSJG',
          fileList: [],
          type: 'input',
          isBitian: true
        },
        {
          name: '村小组意见',
          key: 'CMXZYJ',
          fileList: [],
          type: 'input',
          isBitian: true
        },
        {
          name: '村集体组织、村民委员会意见',
          key: 'CWHYJ',
          text: true,
          type: 'input',
          isBitian: true
        }
      ],
      columns: [],
      formData: {
        GSJG: '经七天公示，无异议',
        SHJG: '48',
        GSYJ: '经七天公示，无异议',
        CMXZYJ: '同意上报审批',
        CWHYJ: '经村委集体审议通过，并公示期满，无异议，现予以上报审批',
        PKID: '',
        SHSJ: this.getDate(true),
        CMXZSHSJ: this.getDate(true),
        CWHSHSJ: this.getDate(true),
        SHR: '',
        SHR2: '',
        SHR3: '',
        F_QTRSJSJ: '',
        F_QTNJSSJ: ''
      },
      rowData: {
        // ROW_GUID:'fb4bb94f-df61-4690-81f4-b751c42c92fb'
      },
      isAdd: true
    }
  },
  methods: {
    //退回
    blackTable: async function () {
      this.$confirm({
        title: '提示',
        message: '是否确定要退件',
        btn: {
          okText: '确定',
          cancelText: '取消'
        }
      })
        .then(() => {
          // do something
          this.tuijian()
        })
        .catch(() => {
          console.log('no')
        })
    },
    async tuijian() {
      this.$router.push({
        path: '/tuijian',
        query: {
          isTuiHui: true,
          data: JSON.stringify(this.rowData)
        }
      })
    },
    download: async function () {
      if (this.isAdd) {
        this.$toast.fail('请先保存数据')
        return
      }
      let params1 = {
        accessCode: '688bd3883572440a859dfd8ba9194e7b',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: {
          dataguid: '74d6dca8-0b5d-47e9-a3bd-c44fdb592732',
          searchObject: JSON.stringify([]),
          token: window.localStorage.getItem('token')
        }
      }
      const res1 = await FileServerProxy(params1)
      let data1 = JSON.parse(res1.data.data).Data
      console.log('11111')
      console.log(data1)
      let url =
        data1[0].F_WAIWANGIP.replace(/#/g, ':') +
        '/PrintServer/api/PreviewWordRpt?groupGuid={684FAD09-788B-4BE6-8B4C-78716A85E88B}&toRowGuid=' +
        this.rowData.ROW_GUID +
        '&dataGuid=01103ebf-a884-4282-b996-78dd64196946'
      let url1 = window.g.BaseURL + '/api/farmerHouse/proxy/dataTransFile/v2?fileUrl=' + encodeURIComponent(url)
      this.$router.push({
        path: './viewPDF',
        query: {
          data: url1
        }
      })
    },
    setValue(value) {
      this.formData.F_QTRSJSJ = value
    },
    setValue1(value) {
      this.formData.F_QTNJSSJ = value
    },
    getColumns: async function () {
      let params = {
        accessCode: '688bd3883572440a859dfd8ba9194e7b',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: {
          dataguid: '2c83190c-56d9-4994-a4a9-df4099bad8f9',
          searchObject: JSON.stringify([]),
          token: window.localStorage.getItem('token')
        }
      }
      debugger
      const res = await FileServerProxy(params)
      let data = JSON.parse(res.data.data).Data
      console.log(data)
      this.columns = data
    },
    onConfirm(data) {
      this.showPicker = false
      this.formData.SHJG = data.DICID
    },
    getList(item) {
      this.groupGuids = item.groupGuid
    },
    afterRead(file) {
      if (Array.isArray(file)) {
        file.forEach((item, index) => {
          this.getFileServerUpload(item.file)
        })
      } else {
        this.getFileServerUpload(file.file)
      }
    },
    getFileServerUpload: async function (file) {
      let data = {
        toRowGuid: this.rowguids,
        groupGuid: this.groupGuids
        // token: window.localStorage.getItem('token')
      }
      let formData = new FormData()
      formData.append('file', file)
      formData.append('accessCode', '7a3fc061c866434b8475d3775c9ddcea')
      formData.append('cityCode', window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000')
      // formData.append('token', window.localStorage.getItem('token'))
      formData.append('paramStr', JSON.stringify(data))
      const res = await dataTransFile(formData)
      let data1 = JSON.parse(res.data.data).FileList
      this.fileGuid = data1[0].FILEGUID
      if (data1[0].FILEGUID) {
        this.$toast.success('上传成功!')
      }
    },
    delectFile: async function (file) {
      debugger
      let fileguid = ''
      if (file.ROW_GUID) {
        fileguid = file.ROW_GUID
      } else {
        fileguid = this.fileGuid
      }
      if (fileguid) {
        let params = {
          accessCode: 'ce9b691634de4ebca68dc5bb638d07f4',
          cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
          params: {
            fileGuid: fileguid,
            token: window.localStorage.getItem('token')
          }
        }
        const res = await FileServerProxy(params)
        let data = JSON.parse(res.data.data).Success
        if (data) {
          this.$toast.success('删除成功!')
        }
      }
    },
    saveData: async function (data1) {
      let data = this.formData
      data.TO_ROW_GUID = this.rowData.ROW_GUID
      let params = {
        accessCode: '',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: {
          dataGuid: '313d5ddd-2c1b-4f55-82e1-84d5effd9c47',
          strParams: JSON.stringify([data]),
          token: window.localStorage.getItem('token')
        }
      }
      if (this.isAdd) {
        params.accessCode = '0fb3f6123d1b4fe6851c99532c463f6f'
        const res = await FileServerProxy(params)
        let data = JSON.parse(res.data.data).Success
        if (data) {
          this.isAdd = false
          if (data1 == 'first') {
            return
          }
          this.$toast.success('成功！')
        }
      } else {
        params.accessCode = '77ad6c1591e54d4fbc45ecc90374a2a2'
        const res = await FileServerProxy(params)
        let data = JSON.parse(res.data.data).Success
        if (data) {
          if (data1 == 'first') {
            return
          }
          this.$toast.success('修改成功!')
        }
      }
    },
    getData: async function () {
      let params = {
        accessCode: '688bd3883572440a859dfd8ba9194e7b',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: {
          dataguid: '313d5ddd-2c1b-4f55-82e1-84d5effd9c47',
          searchObject: JSON.stringify([{ field: 'to_row_guid', value: this.rowData.ROW_GUID, operator: '=' }]),
          token: window.localStorage.getItem('token')
        }
      }
      const res = await FileServerProxy(params)
      let data = JSON.parse(res.data.data).Data
      console.log(data)
      if (data.length > 0) {
        for (let i in this.formData) {
          if (data[0][i]) {
            this.formData[i] = data[0][i]
          }
        }
        this.rowguids = data[0].ROW_GUID
        this.isAdd = false
      } else {
        this.rowguids = this.newGuid()
        this.saveData('first')
        this.isAdd = true
      }
      this.getFile()
    },
    getFile: async function () {
      let groupGuid = []
      this.ImgData.forEach((item) => {
        groupGuid.push(item.groupGuid)
      })
      let params = {
        accessCode: '1fdcbce42c6d4748a020feba618d54b8',
        cityCode: window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000',
        params: {
          groupGuid: groupGuid.join(','),
          toRowGuid: this.rowguids,
          token: window.localStorage.getItem('token')
        }
      }
      const res = await FileServerProxy(params)
      let data = JSON.parse(res.data.data).FilesInfo
      if (data.length > 0) {
        data.forEach((element) => {
          this.ImgData.forEach((item) => {
            if (element.GROUPGUID == item.groupGuid) {
              this.getFileUrl(element, item)
            }
          })
        })
      }
    },
    //获取附件文件流
    getFileUrl: async function (element, item) {
      let formData = new FormData()
      formData.append('accessCode', '98bcf528966e48ce896a8b3fd02d45d5')
      formData.append('cityCode', window.localStorage.getItem('citycode') ? window.localStorage.getItem('citycode') : '441300000000')
      formData.append(
        'paramStr',
        JSON.stringify({
          fileGuid: element.ROW_GUID
        })
      )
      let response = await dataTransFilePreview(formData)
      if (response) {
        var img = new Blob([new Int8Array(response.data, 0)], {
          type: response.headers['content-type']
        }) //type类型可自定义
        element['isImage'] = true
        element['url'] = window.URL.createObjectURL(img)
        item.fileList.push(element)
      }
    },
    getDiffDay(date_1, date_2) {
      // 计算两个日期之间的差值
      let totalDays, diffDate
      let myDate_1 = Date.parse(date_1)
      let myDate_2 = Date.parse(date_2)
      // 将两个日期都转换为毫秒格式，然后做差
      diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
      totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
      // console.log(totalDays)
      return totalDays // 相差的天数
    },
    timestampToTime(times) {
      let time = times[1]
      let mdy = times[0]
      mdy = mdy.split('/')
      let month = parseInt(mdy[0])
      let day = parseInt(mdy[1])
      let year = parseInt(mdy[2])
      return year + '-' + month + '-' + day
    },
    sendData: async function () {
      //判断必填项
      let newArr = {
        GSJG: '公示意见',
        SHJG: '公示结论',
        CMXZYJ: '村小组意见',
        CWHYJ: '村集体组织、村民委员会意见',
        F_QTRSJSJ: '公示开始时间',
        F_QTNJSSJ: '公示结束时间'
      }
      for (let i in newArr) {
        if (!this.formData[i]) {
          this.$toast.fail(newArr[i] + '不能为空')
          return
        }
      }
      if (this.ImgData[2].fileList.length == 0 || this.ImgData[3].fileList.length == 0) {
        this.$toast.fail('请填写必填项')
        return
      }
      this.saveData('first')
      //获取第一条数据返回的CREATEDATE，计算该时间第二天凌晨和当前时间是否<=7天，如果<=7天且当前行X==330324000000提示：公示期未满七天，不允许往下一环节提交！（公示文件最后上传日期：' + CREATEDATE+ '），并且不允许往下一环节发送；否则正常发送
      let data = [{ field: 'house_cwgstj.TO_ROW_GUID', value: this.rowData.TO_ROW_GUID }]
      const res = await GSA_Search('d87b4962-328b-4986-b59a-596c46a44820', data)
      if (res.Data.length > 0 && this.rowData.X == 330324000000) {
        //获取当前时间
        const nowday = this.timestampToTime(time.toLocaleString('en-US', { hour12: false }).split(' '))
        //处理创建时间
        const createdate = this.addDate(res.Data[0].CREATEDATE)
        const num = this.getDiffDay(createdate, nowday)
        if (num <= 7) {
          this.$toast.fail('公示期未满七天，不允许往下一环节提交!(公示文件最后上传日期：' + res.Data[0].CREATEDATE + ')')
          return false
        }
      }
      setTimeout(() => {
        this.$router.push({
          path: '/TreeSelect1',
          query: { data: this.rowData, iscgs: 1 }
        })
      }, 1000)
      // let  userId = ""
      // if (this.rowData.BUILDTYPE==14){
      //   userId = this.rowData.SSZZ
      // }else{
      //   userId = this.rowData.TOWN
      // }
      // let isNHApplyParam = {
      //   procName: "up_townaudit",
      //   dtParams: JSON.stringify([{ I_USERID: userId, I_TYPE: 1 }]),
      //   token: window.localStorage.getItem("token"),
      // };
      // let xcfycjtfnApply = {
      //   accessCode: "69db6bece3a7480592e2ec753d1e335e",
      //   cityCode: window.localStorage.getItem("citycode")
      //     ? window.localStorage.getItem("citycode")
      //     : "441300000000",
      //   params: isNHApplyParam,
      // };
      // const resxcfycjtApply = await FileServerProxy(xcfycjtfnApply);
      // console.log(resxcfycjtApply)
      // let data  = JSON.parse(resxcfycjtApply.data.data).Data;
      // if (data.length>0){
      //   this.$toast.success('提交成功!')
      // }
    }
  },
  mounted() {
    this.rowData = JSON.parse(this.$route.query.data)
    this.getColumns()
    this.getData()
    console.log(this.rowData)

    if (window.localStorage.getItem('userName')) {
      this.username = JSON.parse(window.localStorage.getItem('userName')).userName
    }
  }
}
</script>

<style scoped lang="scss">
#countryPublicity {
  width: 100%;
  height: 95vh;
  overflow-y: auto;
  padding: 10px;
  font-size: 13px;

  .title {
    height: 50px;
    display: flex;
    align-items: center;
  }

  .top {
    height: 50px;
    width: 100%;
    border-bottom: 1px solid #d2d2d2;
    border-top: 1px solid #d2d2d2;
    display: flex;
    align-items: center;
    position: relative;
  }

  .link {
    width: 90px;
    height: 30px;
    line-height: 30px;
    background: #eff6ff;
    border-radius: 4px;
    display: inline-block;
    color: #3f8ffc;
    text-align: center;
    float: right;
    position: absolute;
    right: 0px;
  }

  .line {
    width: 5px;
    height: 26px;
    background: #007aff;
    display: inline-block;
    float: left;
    margin-right: 10px;
  }

  .footer {
    width: 100%;
    text-align: center;
    padding: 10px;
  }
}
</style>
<style lang="scss">
#countryPublicity .upload-pictures2 {
  .van-cell {
    padding: 0;
    /*background: #E7E7E7;*/
  }

  .upload-pictures1 {
    .van-cell {
      /*background: #E7E7E7;*/
    }
  }

  .van-field__label {
    font-weight: bold;
    color: #000;
  }

  .van-cell::after {
    display: none;
  }
}

#countryPublicity .upload-pictures1 {
  .van-cell {
    // padding: 0;
    /*background: #E7E7E7;*/
  }

  .upload-pictures1 {
    .van-cell {
      /*background: #E7E7E7;*/
    }
  }

  .van-field__label {
    font-weight: bold;
    color: #000;
  }

  .van-cell::after {
    display: none;
  }
}
</style>
